package com.yklx.youke.security;

import com.yklx.youke.admin.mapper.PermissionMapper;
import com.yklx.youke.entity.User;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class CustomUserDetails implements UserDetails {

    private final User user;
    private final PermissionMapper permissionMapper;
    private List<GrantedAuthority> authorities;

    public CustomUserDetails(User user, PermissionMapper permissionMapper) {
        this.user = user;
        this.permissionMapper = permissionMapper;
        this.authorities = loadAuthorities();
    }

    private List<GrantedAuthority> loadAuthorities() {
        List<GrantedAuthority> authorities = new ArrayList<>();
        
        // 获取用户的角色权限
        String userId = user.getUserId().toString();
        List<com.yklx.youke.entity.Permission> userPermissions = 
            permissionMapper.getUserPermissions(userId);
        
        // 将权限转换为GrantedAuthority
        if (userPermissions != null) {
            authorities.addAll(userPermissions.stream()
                .map(permission -> new SimpleGrantedAuthority(permission.getPermissionCode()))
                .collect(Collectors.toList()));
        }
        
        // 仍然保留传统角色作为兼容性支持
        if (user.getRoleId() != null) {
            authorities.add(new SimpleGrantedAuthority("ROLE_" + user.getRoleId().name()));
        }
        
        return authorities;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return this.authorities;
    }

    @Override
    public String getPassword() {
        return user.getPasswordHash();
    }

    @Override
    public String getUsername() {
        return user.getUsername();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return user.getStatus() == User.UserStatus.ACTIVE;
    }

    public User getUser() {
        return user;
    }
}